# Copyright (c) 2011 anatanokeitai.com(sakurai_youhei)
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# 
# The Software shall be used for Younger than you, not Older.
# 

import re
import urllib
import time

import pyacp
from pyacd.auth import CustomHTMLParser
from pyacd.auth import Session as OriginalSession

def login(email=None,password=None,session=None):
  if session:
    pyacp.conn.session=Session(session)
  elif email is None or password is None:
    raise TypeError("invalid args email->%s,password->%s"%(email,password))
  else:
    pyacp.conn.session=Session()
  
  end_point="https://www.amazon.com/gp/dmusic/mp3/player?ie=UTF8&ref_=sa_menu_mp3_acp1&"
  html=pyacp.conn.do_get(end_point)

  if email and password:
    begin='<form name="signIn"'
    end='</form>'
    html=begin + html.split(begin,1)[1].split(end,1)[0] +end

    parser=CustomHTMLParser()
    parser.feed(html)
    parser.close()

    action=parser.action
    params=parser.key_value.copy()

    params["create"]=0
    #params["x"]=0
    #params["y"]=0
    #params["metadata1"]=""
    params["email"]=email
    params["password"]=password
    body=urllib.urlencode(params)
    html=pyacp.conn.do_post(action,body,{"Content-Type":"application/x-www-form-urlencoded"})

  try:
    #print html

    ptn_begin = re.compile(r'<script type="text/javascript" >')
    ptn_end = re.compile(r'</script>')
    javascript = html[ptn_begin.search(html).end():]
    javascript = javascript[:ptn_end.search(javascript).start()]
    #print javascript

    ptn = re.compile(r"amznMusic\.customerName.*")
    username = ptn.search(javascript).group().split("'")[1]
    #print username
    pyacp.conn.session.username = username

    ptn = re.compile(r"amznMusic\.customerId.*")
    customer_id = ptn.search(javascript).group().split("'")[1]
    #print customer_id
    pyacp.conn.session.customer_id = customer_id

    ptn = re.compile(r"window\.amznMusic\.did.*")
    device_id = ptn.search(javascript).group().split("'")[1]
    #print device_id
    pyacp.conn.session.device_id = device_id

    ptn = re.compile(r"window\.amznMusic\.dtid.*")
    device_type = ptn.search(javascript).group().split("'")[1]
    #print device_type
    pyacp.conn.session.device_type = device_type

    ptn = re.compile(r"window\.amznMusic\.tid.*")
    token_id = ptn.search(javascript).group().split("'")[1]
    #print token_id
    pyacp.conn.session.token_id = token_id

  except:
    pass
    
  return pyacp.conn.session


class Session(OriginalSession):
  def __init__(self,session=None):
    OriginalSession.__init__(self,session=session)
    self.device_id = None
    self.device_type = None
    self.token_id = None

  def is_logined(self):
    return (OriginalSession.is_logined(self) and self.device_id and self.device_type)

